#include <iostream>
#include "LIB_LOADER.h"

// 为不同平台处理动态链接库的加载 现仅实现Windows的支持
#ifdef _WIN32
#include <windows.h>
QSystem::LIB_VIEW::LIB_VIEW(const std::string& libPath)
{
	int wideCharSize = MultiByteToWideChar(CP_UTF8, 0, libPath.c_str(), -1, NULL, 0);
	std::wstring pathWide(wideCharSize, L'\0');
	MultiByteToWideChar(CP_UTF8, 0, libPath.c_str(), -1, &pathWide[0], wideCharSize);

	_hPtr = (void*)LoadLibraryW(pathWide.c_str());
	if (_hPtr == NULL)
	{
		_hPtr = nullptr;
		throw std::runtime_error("动态链接库加载失败: "+std::string(libPath));
	}
}

void* QSystem::LIB_VIEW::findFunction(const std::string& funcName) const
{
	auto ptr = (void*)GetProcAddress((HMODULE)_hPtr, funcName.c_str());
	if (ptr == NULL)
	{
		throw std::runtime_error("找不到目标函数: "+funcName);
	}
	return ptr;
}

void QSystem::LIB_VIEW::freeLib()
{
	if (_hPtr == nullptr)
	{
		return;
	}
	auto ptr = _hPtr;
	_hPtr = nullptr;
	FreeLibrary((HMODULE)ptr);
}
#endif

QSystem::LIB_VIEW::~LIB_VIEW()
{
	freeLib();
}